package com.bndg.dnttapwhite

import android.content.Context
import android.media.SoundPool

class SoundPlayer(private val context: Context) {

    private lateinit var soundPool: SoundPool
    private val soundMap = HashMap<String, Int>()

    init {
        initializeSoundPool()
    }

    // 初始化 SoundPool 并加载音频文件
    private fun initializeSoundPool() {
        soundPool = SoundPool.Builder()
            .setMaxStreams(7) // 最大同时播放的音符数量
            .build()

        // 加载音符资源文件
        soundMap["do"] = soundPool.load(context, R.raw.do_note, 1)
        soundMap["re"] = soundPool.load(context, R.raw.re_note, 1)
        soundMap["mi"] = soundPool.load(context, R.raw.mi_note, 1)
        soundMap["fa"] = soundPool.load(context, R.raw.fa_note, 1)
        soundMap["sol"] = soundPool.load(context, R.raw.sol_note, 1)
        soundMap["la"] = soundPool.load(context, R.raw.la_note, 1)
        soundMap["si"] = soundPool.load(context, R.raw.si_note, 1)
    }

    // 播放指定音符
    fun playNote() {
        // 随机播放
        val note = when ((1..7).random()) {
            1 -> "do"
            2 -> "re"
            3 -> "mi"
            4 -> "fa"
            5 -> "sol"
            6 -> "la"
            7 -> "si"
            else -> "do"
        }
        val soundId = soundMap[note]
        if (soundId != null) {
            soundPool.play(soundId, 1f, 1f, 1, 0, 1f) // 参数：音量、优先级、循环次数、播放速度
        }
    }

    // 释放资源
    fun release() {
        soundPool.release()
    }
}